package mongo

import (
	"context"
	"encoding/json"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"go.mongodb.org/mongo-driver/bson/primitive"
	mongoDriver "go.mongodb.org/mongo-driver/mongo"
	"time"
)

type User struct {
	ID                 primitive.ObjectID `bson:"_id,omitempty"`
	UserName           string             `bson:"user_name"`
	GridData           string             `bson:"grid_data"`
	ManifestCnt        int                `bson:"manifest_cnt"`
	ExtraManifestCnt   int                `bson:"extra_manifest_cnt"`
	ManifestRecoverCnt int                `bson:"manifest_recover_cnt"`

	ManifestBeginTime int64 `bson:"manifest_begin_time"`
	ManifestEndTime   int64 `bson:"manifest_end_time"`

	Timestamps
}

func NewUser() *User {
	return &User{
		Timestamps: Timestamps{CreatedAt: time.Now(), UpdatedAt: time.Now()},
	}
}

func CreateUser(ctx context.Context, gridData []map[string]interface{}, manifestCnt int) (*User, error) {
	user := NewUser()
	var err error
	var tmp []byte
	tmp, err = json.Marshal(gridData)
	if err != nil {
		hlog.Error(err)
	}
	user.GridData = string(tmp)
	user.ManifestCnt = manifestCnt

	var ret *mongoDriver.InsertOneResult
	ret, err = CollectionUsers.InsertOne(ctx, user)
	if err != nil {
		hlog.Error(err)
		return nil, err
	}

	user.ID = ret.InsertedID.(primitive.ObjectID)
	return user, nil
}

func FindOneUser(ctx context.Context, userName string) (*User, error) {
	return nil, nil
}
